package top.deepdesigner.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.deepdesigner.dto.AccountTraceDTO;
import top.deepdesigner.pojo.DtsAccountTrace;
import top.deepdesigner.pojo.DtsUser;
import top.deepdesigner.service.DtsAccountTraceService;
import top.deepdesigner.service.DtsUserService;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/21 星期三 22:07:06 <br/>
 */
@Service
public class DtsAccountTraceServiceImpl extends ServiceImpl<BaseMapper<DtsAccountTrace>, DtsAccountTrace> implements DtsAccountTraceService {

  @Autowired
  private DtsUserService dtsUserService;

  @Override
  public Long getAccountTraceCount() {
    return this.count();
  }

  @Override
  public List<DtsAccountTrace> getAccountTraceList(Integer page, Integer limit, String sort, String order, Integer[] statusArray, String username, String mobile) {
    List<DtsUser> dtsUsers = null;
    if (!StringUtils.isEmpty(username)) {
      dtsUsers = dtsUserService.getUserByName(username);
    }
    QueryWrapper<DtsAccountTrace> wrapper = new QueryWrapper<>();

    if (dtsUsers != null) {
      wrapper.in(true, "user_id", dtsUsers.stream().map(DtsUser::getId).collect(Collectors.toList()));
    }
    wrapper
        .in(statusArray.length > 0, "status", Arrays.asList(statusArray))
        .like(!StringUtils.isEmpty(mobile), "mobile", mobile)
        .orderBy(true, "asc".equalsIgnoreCase(order), sort);
    Page<DtsAccountTrace> userPage = new Page<>(page, limit);
    return this.page(userPage, wrapper).getRecords();
  }

  @Override
  @Transactional
  public Boolean approveAgency(AccountTraceDTO accountTraceDTO) {
    DtsAccountTrace dtsAccountTrace = new DtsAccountTrace();
    dtsAccountTrace.setStatus(accountTraceDTO.getStatus());
    dtsAccountTrace.setTraceMsg(accountTraceDTO.getTraceMsg());
    dtsAccountTrace.setUpdateTime(new Date());
    return this.update(dtsAccountTrace,
        new LambdaUpdateWrapper<DtsAccountTrace>().eq(DtsAccountTrace::getId, accountTraceDTO.getId()));
  }
}
